﻿#include "emotionwidget.h"
#include <QDomDocument>
#include <QFile>
#include <QImage>
#include <QKeyEvent>
#include <QMap>
#include <QPixmap>
#include "emotionresource.h"
#include "globaltools.h"

EmotionWidget::EmotionWidget(QWidget *parent) : QListWidget(parent)
{
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setDragDropMode(QAbstractItemView::NoDragDrop);

    setMovement(QListView::Static);
    setResizeMode(QListView::Adjust);
    setViewMode(QListView::IconMode);
    setUniformItemSizes(true);

    setFrameStyle(QFrame::NoFrame);
    setStyleSheet(QLatin1Literal("QListWidget{border-top:none;border-right:1px solid #dfe5e8}"));

    auto emotions = EmotionResource::instance();

    int height = 50;
    int rows = 2;
    int columns = (emotions->size() + rows - 1) / rows;
    int width = (Emotion::size.width() + 6) * columns;

    resize(width + 3, height + 2);

    for(auto it = emotions->constBegin(); it != emotions->constEnd(); it++)
    {
        const auto & value = it.value();
        if(value.name.isEmpty())
            continue;
        auto item = new QListWidgetItem(this);
        item->setData(Qt::DecorationRole, value.pixmap);
        item->setData(Qt::UserRole, value.fileName);
        item->setData(Qt::ToolTipRole, value.name);
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
    }
}

void EmotionWidget::focusOutEvent(QFocusEvent *e)
{
    QListWidget::focusOutEvent(e);
    if(isVisible())
        hide();
}

void EmotionWidget::keyPressEvent(QKeyEvent *e)
{
#if QT_VERSION >= QT_VERSION_CHECK(5,6,0)
    if(e->matches(QKeySequence::Cancel))
#else
    if(QKeySequence((e->modifiers() | e->key()) & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier)).matches(QKeySequence(Qt::Key_Escape)) == QKeySequence::ExactMatch)
#endif
        clearFocus();
    else
        QListWidget::keyPressEvent(e);
}
